package com.xyz.config;

import com.xyz.dao.UserDao;
import com.xyz.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import javax.swing.*;

//自定义的 realm 类
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserDao userDao;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=》授权 doGetAuthorizationInfo");
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //拿到当前登录的这个对象
        Subject subject= SecurityUtils.getSubject();
        //拿到user对象
        User currentUser=(User) subject.getPrincipal();
        //给权限
        if(currentUser.getPassword()!=null){
            info.addStringPermission(currentUser.getPhone());
            return info;
        }else{
            return null;
        }

    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=》认证 doGetAuthenticationInfo");
        UsernamePasswordToken userToken=(UsernamePasswordToken) authenticationToken;
        User user=userDao.findUserid(userToken.getUsername());
        if(user!=null){
            if(userToken.getUsername().equals(user.getName())){
                //密码可以加密： md5  md5盐值加密
                return new SimpleAuthenticationInfo(user,user.getPassword(),"");
            }
        }
        return null;//抛出异常密码错误
    }
}
